package com.jsb.laundry.service.designpatterns.adapter.loginservice.impl;

import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.http.EncryptUtil;
import com.jsb.laundry.dao.RiderUserInfoDao;
import com.jsb.laundry.model.dto.LoginRequest;
import com.jsb.laundry.model.dto.UserInfoRequest;
import com.jsb.laundry.model.vo.LoginUserInfoVo;
import com.jsb.laundry.service.LoginService;
import com.jsb.laundry.service.designpatterns.adapter.loginservice.LoginAdapter;
import com.jsb.laundry.thirdpartyinterfaces.WxThirdPartyInterfacesService;
import com.jsb.laundry.thirdpartyinterfaces.dto.LoginVo;
import com.jsb.laundry.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.concurrent.TimeUnit;

/**
 * 微信登录适配器
 */
@Service
public class LoginForWechatAdapter implements LoginAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginForWechatAdapter.class);
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private WxThirdPartyInterfacesService wxThirdPartyInterfacesService;
    @Autowired
    private LoginService loginService;
    @Resource
    private RiderUserInfoDao userInfoDao;
    /**
     * 登录逻辑处理
     *
     * @param loginRequest
     * @return
     */
    @Override
    public  LoginUserInfoVo login(LoginRequest loginRequest) {
        //查询openid unionid
        LoginVo login = wxThirdPartyInterfacesService.login(loginRequest.getWxLoginCode());
        //查询手机号
        String userPhone = wxThirdPartyInterfacesService.getPhone(loginRequest.getWxLoginGetPhoneCode());
        //根据openid查询userid
        String userId = loginService.findByUserId(login.getOpenid());
        if (JSBUtil.isEmptyString(userId)) {
            //注册用户
            UserInfoRequest userInfoRequest = new UserInfoRequest();
            String uuid = JSBUtil.generateUUID();
            userInfoRequest.setUserId(uuid);
            userInfoRequest.setUserImg("https://jsb-wx.oss-cn-shanghai.aliyuncs.com/userInfo/ad978ba5afa748e2ab1b94a0d9708296.png");
            userInfoRequest.setUserName("普通用户");
            userInfoRequest.setUserPhone(userPhone);
            userInfoRequest.setOpenId(login.getOpenid());
            userInfoRequest.setUnionId(login.getUnionid());
            //判断有邀请人 添加到个人信息里面
            if (!JSBUtil.isEmptyString(loginRequest.getInviterId())){
                //根据id查询userId
                String userInfoId = userInfoDao.getRiderInfoId(loginRequest.getInviterId());
                loginRequest.setInviterId(userInfoId);
                userInfoRequest.setParentId(loginRequest.getInviterId());
            }
            loginService.addUser(userInfoRequest);
            loginService.addCapitalAccount(uuid);
            //向银行卡添加用户信息
            loginService.addUserInfoForBank(uuid);


            //查看邀请人是否是我们平台的用户
            String inviterOpenId = loginService.findByOpenId(loginRequest.getInviterId());
            //存在邀请人id 添加邀请记录

            userId = uuid;
            if ((!JSBUtil.isEmptyString(loginRequest.getInviterId())
                    || !"undefined".equals(loginRequest.getInviterId())
                    || !"null".equals(loginRequest.getInviterId()))
                    && !userId.equals(loginRequest.getInviterId())
                    && !JSBUtil.isEmptyString(inviterOpenId)) {
                LOGGER.info("用户：{},邀请了,新用户：{}", loginRequest.getInviterId(), userId);
                loginService.addRiderPromotion(loginRequest.getInviterId(), userId); // rider_promotion
                /**
                 * 等级晋升
                 */
                LevelPromotion.levelPromotion(loginRequest.getInviterId());
            }


        }
        //如果存在返回个人信息和token
        LoginUserInfoVo.UserInfo userInfo = loginService.findUserInfo(userId);
        //token过期时间戳
        long tokenExpireTimestamp = LocalDateTime.now().plusDays(30).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        //TODO token生成处(uuid + userId() + timestamp(token过期的时间戳) )
        String token = "wx_rider_Authorization: " + JSBUtil.generateUUID() + ". " + EncryptUtil.Base64Tool.base64Encode(userId) + ". " + EncryptUtil.Base64Tool.base64Encode(String.valueOf(tokenExpireTimestamp));
        //存在redis数据库
        redisUtil.setCacheObject(token, userId, 30, TimeUnit.DAYS);
        LoginUserInfoVo loginUserInfoVo = new LoginUserInfoVo();
        loginUserInfoVo.setToken(token);
        loginUserInfoVo.setUserInfo(userInfo);
        return loginUserInfoVo;
    }
}
